const fs = require('fs');
const QualificationDao = require('../dao/qualification');
const { verifyJWT } = require('./jwt');
const dbm = require('../config/dbModels');
const {aseDecode}=require('../core/crypto')
class WsjAuth {
    constructor(level) {
        //该level表示用户需要有该level的值,才能放行
        this.level = level
    }
    get w() {
        /**
         * 该函数只负责通行或报错终止程序
        */
        return async (ctx, next) => {
            //arr_qualifications形如[{id:23,name:"查看订单"},{id:56,name:"查看用户"}]
            let arr_qualifications = await new Promise((resolve) => {
                fs.readFile('./config/qualification.txt', 'utf-8', async function (err, data) {
                    let arr_allQualification = null;
                    arr_allQualification = err ? await QualificationDao.getAllQualification() : JSON.parse(data).qua
                    resolve(arr_allQualification)
                })
            })
            let jwtStr=verifyJWT(ctx)
            let userId=0
            if(jwtStr.exp<Date.now()){
              userId=aseDecode(jwtStr.id)
            }

            var dbRes = await dbm.User.findOne({
                raw:true,
                where: {
                    id :userId
                },
                attributes:['qualification']
            })
            var userQua=[]
            if (dbRes && dbRes.qualification) {
                userQua= dbRes.qualification.split(',')
            }
            if (userQua.includes(this.level+'')) {
                await next()
            } else {
                throw new global.errs.Forbidden('经检验,尔等无权访问')
            }
        }
    }
}

module.exports = WsjAuth
